/*
 * @Author: cls
 * @Date:   2018-07-12 10:41:43
 * @Last Modified by:   cls
 * @Last Modified time: 2018-10-30 10:28:01
 */
// 判断手机号
import api from '@/api/api.js'
export function isPhoneAvailable(str) {
  var myreg = /^[1][2,3,4,5,6,7,8,9][0-9]{9}$/
  if (!myreg.test(str)) {
    return false
  } else {
    return true
  }
}
// 格式化时间
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') {
      return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}
// 对比时间
export function formatTime(time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()
  const diff = (now - d) / 1000
  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    const h = d.getHours() < 10 ? '0' + d.getHours() : d.getHours()
    const m = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes()
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + h + '时' + m + '分'
  }
}
// 判断终端
const u = navigator.userAgent
export const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 // android终端
export const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios终端
export const browserInfo = function() {
  var json = {
    userAgent: navigator.userAgent.toLowerCase(),
    isAndroid: Boolean(navigator.userAgent.match(/android/gi)),
    isIphone: Boolean(navigator.userAgent.match(/iphone|ipod/gi)),
    isIpad: Boolean(navigator.userAgent.match(/ipad/gi)),
    isWeixin: Boolean(navigator.userAgent.match(/MicroMessenger/gi))
  }
  return json
}
export function stringLength(val) {
  var len = 0
  if (val) {
    for (var i = 0; i < val.length; i++) {
      var a = val.charAt(i)
      if (a.match(/[^\x00-\xff]/gi) != null) {
        len += 2
      } else {
        len += 1
      }
    }
    return len
  } else {
    return len
  }
}
// 微信分享JSSDK
export function weixinShare(share) {
  const url = window.location.href
  api.post('/share/weixin', { url: url }).then(res => {
    let obj = {}
    obj = res.data
    wx.config({
      debug: false,
      appId: obj.appId,
      timestamp: obj.timestamp,
      nonceStr: obj.nonceStr,
      signature: obj.signature,
      jsApiList: [
        // 所有要调用的 API 都要加到这个列表中
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'onMenuShareQQ',
        'onMenuShareWeibo',
        'onMenuShareQZone'
      ]
    })
    wx.ready(function() {
      wx.onMenuShareTimeline({
        title: share.title, // 分享标题
        link: share.url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: share.image, // 分享图标
        success: function() {
          // 用户点击了分享后执行的回调函数
        }
      })
      wx.onMenuShareAppMessage({
        title: share.title, // 分享标题
        desc: share.content, // 分享描述
        link: share.url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: share.image, // 分享图标
        type: 'link', // 分享类型,music、video或link，不填默认为link
        dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
        success: function() {
          // 用户点击了分享后执行的回调函数
        }
      })
      wx.onMenuShareQQ({
        title: share.title, // 分享标题
        desc: share.content, // 分享描述
        link: share.url, // 分享链接
        imgUrl: share.image, // 分享图标
        success: function() {
          // 用户确认分享后执行的回调函数
        },
        cancel: function() {
          // 用户取消分享后执行的回调函数
        }
      })
      wx.onMenuShareQZone({
        title: share.title, // 分享标题
        desc: share.content, // 分享描述
        link: share.url, // 分享链接
        imgUrl: share.image, // 分享图标
        success: function() {
          // 用户确认分享后执行的回调函数
        },
        cancel: function() {
          // 用户取消分享后执行的回调函数
        }
      })
    })
    setShareInfo({
      title: share.title,
      summary: share.content,
      pic: share.image, // 图片
      url: share.url, // 地址栏url，要在域名里的页面
      WXconfig: {
        swapTitleInWX: true,
        appId: obj.appId,
        timestamp: obj.timestamp,
        nonceStr: obj.nonceStr,
        signature: obj.signature
      }
    })
  })
}
export const countTime = (end, nowTime) => {
  // 获取当前时间
  if (typeof end !== 'object') {
    if (('' + end).length === 10) end = parseInt(end) * 1000
  }
  // 判定服务器时间
  if (nowTime && typeof nowTime !== 'object') {
    if (('' + nowTime).length === 10) {
      nowTime = parseInt(nowTime) * 1000
    }
  }
  const date = nowTime ? new Date(nowTime) : new Date()
  const now = date.getTime()
  // 时间差
  const leftTime = end - now
  // 定义变量 d,h,m,s保存倒计时的时间
  let d = 0
  let h = 0
  let m = 0
  let s = 0
  if (leftTime >= 0) {
    d = Math.floor(leftTime / 1000 / 60 / 60 / 24)
    h = Math.floor((leftTime / 1000 / 60 / 60) % 24)
    m = Math.floor((leftTime / 1000 / 60) % 60)
    s = Math.floor((leftTime / 1000) % 60)
  }
  // h = d * 24 + h
  h = h > 9 ? h : '0' + h
  m = m > 9 ? m : '0' + m
  s = s > 9 ? s : '0' + s
  // 递归每秒调用countTime方法，显示动态时间效果
  // setTimeout(() => countTime(end), 1000)
  return {
    d: d,
    h: h,
    m: m,
    s: s
  }
}
